package com.xinchuang.util;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.entity.targetSystem.external.ExternalTarget;
import com.xinchuang.entity.targetSystem.object.CommonAdd;
import com.xinchuang.entity.targetSystem.object.SpecialAdd;
import com.xinchuang.entity.targetSystem.system.CommonAttribute;
import com.xinchuang.entity.targetSystem.system.SpecialAttribute;
import com.xinchuang.entity.targetSystem.system.Target;
import com.xinchuang.entity.targetSystem.weapon.WeaponAttribute;
import com.xinchuang.sqlite.entity.TargetData;
import com.xinchuang.sqlite.entity.TargetElseData;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.Collator;
import java.util.*;

/**
 * @ClassName FileElseUtil
 * @Description: TODO(文件操作工具)
 * @Author zhangxuan
 * @Date 2021-01-14 11:44
 * @Verion V1.0
 */
public class FileElseUtil {

    private static SnowflakeIdWorker snow = new SnowflakeIdWorker(1, 1);

    /**
     * @return int
     * @author zhangxuan
     * @Description TODO 根据文件目录判断文件数量
     * @Date 12:16 2021/1/14
     * @Param [url, number]
     **/
    public static int juageFileNumber(String url, int number) {
        if (!FileUtil.exist(url + File.separator + number)) {
            FileUtil.mkdir(url + File.separator + number);
            return number;
        } else {
            if (FileUtil.loopFiles(url + File.separator + number).size() >= 1024) {
                number++;
                juageFileNumber(url, number);
            }
        }
        return number;
    }


    /**
     * 字符串转换List
     *
     * @param stringList
     * @return
     */
    public static List getStringTransitionList(String stringList) {
        if (StringUtils.isBlank(stringList)) {
            return new ArrayList();
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper. readValue(stringList, List.class);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList();
        }
    }

    /**
     * 字符串转换List
     *
     * @param obj
     * @return
     */
    public static List getObjectToList(Object obj) {
        if (ObjectUtil.isEmpty(obj)) {
            return ListUtil.empty();
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(obj.toString(), List.class);
        } catch (Exception e) {
            return ListUtil.empty();
        }
    }

    /**
     * 字符串转换double
     *
     * @param stringInt
     * @return
     */
    public static double getStringTransitionDouble(String stringInt) {
        try {
            if (StringUtils.isBlank(stringInt)) {
                return 0;
            }
            return Double.valueOf(stringInt);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 字符串转换double
     *
     * @param obj
     * @return
     */
    public static double getObjectToDouble(Object obj) {
        try {
            if (ObjectUtil.isEmpty(obj)) {
                return 0;
            }
            BigDecimal bigDecimal = new BigDecimal(Double.valueOf(obj.toString()));
            return bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 字符串转换int
     *
     * @param obj
     * @return
     */
    public static int getObjectToInt(Object obj) {
        try {
            if (ObjectUtil.isEmpty(obj)) {
                return 0;
            }
            return Integer.valueOf(obj.toString()).intValue();
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 字符串转换double
     *
     * @param stringInt
     * @return
     */
    public static boolean isDouble(String stringInt) {
        try {
            if (StringUtils.isBlank(stringInt)) {
                return false;
            }
            Double.valueOf(stringInt);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String getStringTransitionString(String str) {
        try {
            if (StringUtils.isBlank(str)) {
                return "";
            }
            return str;
        } catch (Exception e) {
            return "";
        }
    }

    public static String getObjectToString(Object obj) {
        try {
            if (ObjectUtil.isEmpty(obj)) {
                return "";
            }
            return obj.toString();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * @param base64
     * @param saveUrl
     * @return
     */
    public static String generateImage(String base64, String saveUrl) {
        if (StringUtils.isBlank(base64)) {
            return null;
        }
        try {
            String[] format = base64.split(",");
            String type = format[0].split(";")[1];
            if (type.equals("base64")) {
                String suffix = format[0].split(";")[0].split("/")[1];
                //base64解码
                byte[] bytes = Base64.getDecoder().decode(format[1]);
                for (int i = 0; i < bytes.length; i++) {
                    if (bytes[i] < 0) {
                        bytes[i] += 256;
                    }
                }
                String fileName = snow.nextId() + "";
                FileUtil.mkdir(saveUrl);
                OutputStream out = new FileOutputStream(saveUrl + "/" + fileName + "." + suffix);
                out.write(bytes);
                out.flush();
                out.close();
                String result = "/icon/" + fileName + "." + suffix;
                return result;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 用户名MD5加密
     *
     * @param username
     * @return
     */
    public static String keyMD5(String username) {
        return MD5.create().digestHex("ZKWC" + username, "UTF-8");
    }

    public static List<TargetData> getSubTarget(String subId, String subName) {
        String[] key = {"targetName", "position", "height", "area", "desicribe", "plotinfoobj", "grade", "newimageUrl", "targetClassify"};
        String[] name = {"名称", "经纬度", "高程", "面积", "描述", "标绘信息", "目标等级", "图片", "类别"};
        String[] type = {"text", "text", "text", "text", "textarea", "text", "text", "img", "select"};
        String[] value = {
                subName,
                "[0,0,0]",
                "0",
                "",
                "",
                "[]",
                "",
                "[]",
                ""
        };
        String[] remark = {
                "",
                "",
                "",
                "m",
                "㎡",
                "",
                "",
                "",
                "",
                ""
        };
        List<TargetData> list = new ArrayList<>();
        for (int i = 0; i < key.length; i++) {
            TargetData targetData = new TargetData();
            targetData.setId(snow.nextId() + "");
            targetData.setKey(key[i]);
            targetData.setKeyName(name[i]);
            targetData.setKeyType(type[i]);
            targetData.setKeyValue(value[i]);
            targetData.setRemark(remark[i]);
            list.add(targetData);
        }
        return list;
    }

    public static List<TargetData> getSqliteTarget(ExternalTarget externalTarget) {
        String[] key = {"targetName", "country", "position", "height", "area", "desicribe", "plotinfoobj", "grade", "newimageUrl", "targetClassify"};
        String[] name = {"名称", "国家/地区", "经纬度", "高程", "面积", "描述", "标绘信息", "目标等级", "图片", "类别"};
        String[] type = {"text", "text", "text", "text", "text", "textarea", "text", "text", "img", "select"};
        String[] value = {
                externalTarget.getTargetName(),
                "\"" + externalTarget.getCountry() + "\"",
                "[" + externalTarget.getLon() + "," + externalTarget.getLat() + "," + 0 + "]",
                "0",
                "",
                "",
                "[]",
                "一级",
                "[]",
                externalTarget.getType()
        };
        String[] remark = {
                "",
                "",
                "",
                "m",
                "㎡",
                "",
                "",
                "",
                "",
                ""
        };
        List<TargetData> list = new ArrayList<>();
        for (int i = 0; i < key.length; i++) {
            TargetData targetData = new TargetData();
            targetData.setId(snow.nextId() + "");
            targetData.setKey(key[i]);
            targetData.setKeyName(name[i]);
            targetData.setKeyType(type[i]);
            targetData.setKeyValue(value[i]);
            targetData.setRemark(remark[i]);
            targetData.setPerson("main-system");
            targetData.setSource("api-port");
            list.add(targetData);
        }
        return list;
    }

    public static List<Map<String, Object>> getBaseList() {
        String[] key = {"targetName", "coordinates", "country", "area", "class", "targetType"};
        String[] name = {"目标名称", "坐标系", "国家地区", "区域", "等级", "类型"};
        String[] type = {"string", "string", "string", "string", "string", "string"};
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < key.length; i++) {
            Map<String, Object> m = new HashMap<>();
            m.put("keyName", name[i]);
            m.put("key", key[i]);
            m.put("keyType", type[i]);
            m.put("showType", "text");
            m.put("required", "false");
            m.put("info", "false");
            m.put("dataRange", "[-180,180]");
            m.put("hideen", "false");
            m.put("message", "当前值为默认选项");
            list.add(m);
        }
        return list;
    }

    public static Map<String, Object> getBaseList(Map<String, Object> map) {
        String[] key = {"targetName", "lon", "lat", "coordinates", "country", "area", "class", "targetType", "targetId", "height"};
        Map<String, Object> m = new HashMap<>();
        for (int i = 0; i < key.length; i++) {
            m.put(key[i], map.get(key[i]));
        }
        return m;
    }

    public static List<TargetElseData> getSqliteTargetElse(List<String> key, List<String> name, Map<String, Object> map, String targetId, int taskId) {
        List<TargetElseData> list = new ArrayList<>();
        for (int i = 0; i < key.size(); i++) {
            TargetElseData elseData = new TargetElseData();
            elseData.setId(String.valueOf(snow.nextId()));
            elseData.setAchievementId(targetId);
            elseData.setKey(key.get(i));
            elseData.setKeyName(name.get(i));
            elseData.setKeyType("String");
            elseData.setKeyValue(ObjectUtil.isNotEmpty(map.get(key.get(i))) ? map.get(key.get(i)).toString() : "");
            elseData.setRemark("");
            elseData.setPerson("");
            elseData.setSource("api-port");
            list.add(elseData);
        }
        return list;
    }

    public static List<Map<String, Object>> getDetailList(List<String> key, List<String> name) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < key.size(); i++) {
            Map<String, Object> m = new HashMap<>();
            m.put("keyName", name.get(i));
            m.put("key", key.get(i));
            m.put("keyType", "string");
            m.put("showType", "textarea");
            m.put("required", "false");
            m.put("info", "false");
            m.put("dataRange", "[0,2000]");
            m.put("hideen", "false");
            m.put("message", "当前值为默认选项");
            list.add(m);
        }
        return list;
    }

    public static Map<String, Object> getDetailList(List<String> key, Map<String, Object> map) {
        Map<String, Object> m = new HashMap<>();
        for (int i = 0; i < key.size(); i++) {
            m.put(key.get(i), map.get(key.get(i)));
        }
        return m;
    }

    public static List<Object> countryList() {
        ArrayList<Object> list = new ArrayList<>();
        String[] countryList = {"中国台湾", "日本", "朝鲜", "韩国", "美国", "印度", "俄罗斯", "越南", "菲律宾", "马来西亚"};
        Comparator cmp = Collator.getInstance(Locale.CHINA);
        String[] elseCountry = {"中国", "蒙古", "北韩", "缅甸", "文莱", "柬埔寨", "东帝汶", "印度尼西亚", "寮国", "老挝", "新加坡", "泰国", "孟加拉国", "不丹", "马尔地夫", "尼泊尔", "巴基斯坦", "斯里兰卡", "哈萨克斯坦", "吉尔吉斯斯坦", "塔吉克斯坦", "土库曼斯坦", "乌兹别克斯坦", "阿富汗", "亚美尼亚", "亚美尼亚", "亚塞拜然", "阿塞拜疆", "巴林", "塞浦路斯", "塞浦路斯 - 北塞浦路斯", "北塞浦路斯", "乔治亚", "格鲁吉亚", "伊朗", "伊拉克", "以色列", "约旦", "科威特", "黎巴嫩", "阿曼", "巴勒斯坦", "卡达", "卡塔尔", "沙特阿拉伯", "叙利亚", "叙利亚", "土耳其", "阿拉伯联合大公国", "阿拉伯联合酋长国", "也门", "比利时", "法国", "爱尔兰", "卢森堡", "摩纳哥", "荷兰", "英国", "丹麦", "芬兰", "冰岛", "瑞典", "奥地利", "捷克", "德国", "匈牙利", "列支敦士登", "波兰", "斯洛伐克", "瑞士", "白俄罗斯", "爱沙尼亚", "拉脱维亚", "立陶宛", "摩尔多瓦", "乌克兰", "阿尔巴尼亚", "安道尔", "波斯尼亚和黑塞哥维那", "保加利亚", "克罗地亚", "克罗埃西亚", "塞浦路斯", "希腊", "意大利", "马其顿", "马耳他", "葡萄牙", "罗马尼亚", "圣马利诺", "塞尔维亚和黑山", "塞尔维亚与蒙特内哥罗", "斯洛文尼亚", "西班牙", "梵蒂冈", "教廷", "加拿大", "墨西哥", "贝里斯", "伯利兹", "哥斯达黎加", "萨尔瓦多", "危地马拉", "洪都拉斯", "尼加拉瓜", "巴拿马", "安地卡及巴布达", "安提瓜和巴布达", "巴哈马", "巴贝多", "巴巴多斯", "古巴", "多米尼克", "多米尼加联邦", "多米尼加", "多米尼加共和国", "格瑞纳达", "格林纳达", "海地", "牙买加", "圣克里斯多福及尼维斯", "圣基茨和尼维斯", "圣露西亚", "圣卢西亚", "圣文森及格瑞那丁", "圣文森特和格林纳丁斯", "千里达及托巴哥", "特立尼达和多巴哥", "阿根廷", "玻利维亚", "巴西", "智利", "哥伦比亚", "厄瓜多尔", "盖亚那", "圭亚那", "秘鲁", "巴拉圭", "苏利南", "苏里南", "乌拉圭", "委内瑞拉", "安圭拉(英国)", "阿鲁巴", "阿鲁巴(荷兰)", "英属维尔京群岛(英国)", "百幕达", "百慕大(英国)", "开曼群岛", "开曼群岛(英国)", "福克兰群岛", "马尔维纳群岛(英国)", "法属圭亚纳(法国)", "格陵兰(丹麦)", "瓜德洛普", "瓜德卢普(法国)", "扬马延岛(挪威)", "马提尼克(法国)", "蒙特塞拉特(英国)", "纳弗沙岛(美国)", "圣皮耶与密克隆群岛(法国)", "荷属安地列斯", "安的列斯(荷兰)", "波多黎各(美国)", "南乔治亚与南三明治群岛(英国)", "特克斯与凯科斯群岛(英国)", "维京群岛(美国)", "波怀特岛(挪威)", "法属南方与南极领地(法国)", "贺得及麦唐纳群岛(澳大利亚)", "彼得一世岛(挪威)", "阿尔及利亚", "埃及", "利比亚", "摩洛哥", "苏丹", "突尼西亚", "贝宁", "布吉纳法索", "布基纳法索", "查德", "乍得", "科特迪瓦", "甘比亚", "冈比亚", "加纳", "几内亚", "几内亚比索", "赖比瑞亚", "利比里亚", "马里", "尼日", "尼日尔", "毛里塔尼亚", "奈及利亚", "尼日利亚", "塞内加尔", "狮子山", "塞拉利昂", "多哥", "维德角", "佛得角", "喀麦隆", "中非", "赤道几内亚", "加彭", "加蓬", "刚果共合国", "刚果民主共和国", "刚果民主共和国", "圣多美普林西比", "安哥拉", "波札那", "博茨瓦纳", "葛摩", "科摩罗", "赖索托", "莱索托", "马达加斯加", "马拉维", "模里西斯", "毛里求斯", "莫桑比克", "纳米比亚", "史瓦济兰", "斯威士兰", "南非", "坦尚尼亚", "赞比亚", "津巴布韦", "蒲隆地", "布隆迪", "吉布地", "吉布提", "厄利垂亚", "厄立特里亚", "伊索比亚", "埃塞俄比亚", "肯亚", "肯尼亚", "卢安达", "卢旺达", "塞席尔", "塞舌尔", "索马利亚", "索马里", "坦桑尼亚", "乌干达", "加纳利群岛(西班牙)", "休达及美利里亚(西班牙", "争议区)", "马德拉(葡萄牙)", "马约特岛(法国)", "留尼旺", "留尼汪(法国)", "圣赫伦那", "圣赫勒拿(英国)", "西撒哈拉(摩洛哥", "争议区)", "澳大利亚", "斐济", "吉里巴斯", "马绍尔群岛", "密克罗尼西亚", "瑙鲁", "诺鲁", "新西兰", "帕劳", "帛琉", "巴布亚新几内亚", "萨摩亚", "萨摩亚", "所罗门群岛", "索罗门群岛", "东加", "图瓦卢", "瓦努阿图", "万那杜"};
        Arrays.sort(elseCountry, cmp);
        list.addAll(Arrays.asList(countryList));
        list.addAll(Arrays.asList(elseCountry));
        return list;
    }

    /**
     * 将共有属性接收转化为保存值
     */
    public static CommonAttribute getCommonAttributeByAdd(CommonAdd commonAdd) {
        CommonAttribute commonAttribute = new CommonAttribute();
        commonAttribute.setId(commonAdd.getId());
        commonAttribute.setKeyName(commonAdd.getKeyName());
        commonAttribute.setKey(commonAdd.getKey());
        commonAttribute.setKeyType(commonAdd.getKeyType());
        commonAttribute.setShowType(commonAdd.getShowType());
        commonAttribute.setRequired(commonAdd.getRequired());
        commonAttribute.setInfo(commonAdd.getInfo());
        commonAttribute.setDataRange(commonAdd.getDataRange());
        commonAttribute.setVerify(commonAdd.getVerify());
        commonAttribute.setMin(commonAdd.getMin());
        commonAttribute.setMax(commonAdd.getMax());
        commonAttribute.setEnumerator(commonAdd.getEnumerator().toString());
        commonAttribute.setRow(commonAdd.getRow());
        commonAttribute.setSign(commonAdd.getSign());
        commonAttribute.setMessage(commonAdd.getMessage());
        return commonAttribute;
    }

    /**
     * 将私有属性接收转化为保存值
     */
    public static SpecialAttribute getSpecialAttributeByAdd(SpecialAdd specialAdd) {
        SpecialAttribute specialAttribute = new SpecialAttribute();
        specialAttribute.setId(specialAdd.getId());
        specialAttribute.setTypeId(specialAdd.getTypeId());
        specialAttribute.setKeyName(specialAdd.getKeyName());
        specialAttribute.setKey(specialAdd.getKey());
        specialAttribute.setKeyType(specialAdd.getKeyType());
        specialAttribute.setShowType(specialAdd.getShowType());
        specialAttribute.setRequired(specialAdd.getRequired());
        specialAttribute.setInfo(specialAdd.getInfo());
        specialAttribute.setDataRange(specialAdd.getDataRange());
        specialAttribute.setVerify(specialAdd.getVerify());
        specialAttribute.setMin(specialAdd.getMin());
        specialAttribute.setMax(specialAdd.getMax());
        specialAttribute.setEnumerator(null != specialAdd.getEnumerator() ? specialAdd.getEnumerator().toString() : "");
        specialAttribute.setRow(specialAdd.getRow());
        specialAttribute.setMessage(specialAdd.getMessage());
        specialAttribute.setSort(specialAdd.getSort());
        return specialAttribute;
    }

    /**
     * 将武器库属性接收转化为保存值
     */
    public static WeaponAttribute getWeaponAttributeByAdd(SpecialAdd specialAdd) {
        WeaponAttribute weaponAttribute = new WeaponAttribute();
        weaponAttribute.setId(specialAdd.getId());
        weaponAttribute.setTypeId(specialAdd.getTypeId());
        weaponAttribute.setKeyName(specialAdd.getKeyName());
        weaponAttribute.setKey(specialAdd.getKey());
        weaponAttribute.setKeyType(specialAdd.getKeyType());
        weaponAttribute.setShowType(specialAdd.getShowType());
        weaponAttribute.setRequired(specialAdd.getRequired());
        weaponAttribute.setInfo(specialAdd.getInfo());
        weaponAttribute.setDataRange(specialAdd.getDataRange());
        weaponAttribute.setVerify(specialAdd.getVerify());
        weaponAttribute.setMin(specialAdd.getMin());
        weaponAttribute.setMax(specialAdd.getMax());
        weaponAttribute.setEnumerator(null != specialAdd.getEnumerator() ? specialAdd.getEnumerator().toString() : "");
        weaponAttribute.setRow(specialAdd.getRow());
        weaponAttribute.setMessage(specialAdd.getMessage());
        weaponAttribute.setSort(specialAdd.getSort());
        return weaponAttribute;
    }

    /**
     * 判断目标数据
     *
     * @param table
     * @return
     */
    public static Result targetError(Target table) {
        if (StringUtils.isBlank(table.getTargetName())) {
            return ResultUtil.error(1000, "目标数据名称不能为空");
        } else if (StringUtils.isBlank(table.getCountry())) {
            return ResultUtil.error(1000, "目标数据国家不能为空");
        } else if (StringUtils.isBlank(table.getTargetClassify())) {
            return ResultUtil.error(1000, "目标数据类型不能为空");
        } else if (StringUtils.isBlank(table.getCountry())) {
            return ResultUtil.error(1000, "目标数据国家不能为空");
        }
        return null;
    }


    public static List<Object> getTargetElseAttribute(String typeName) {
        List<Object> lists = new ArrayList<>();
        if (StringUtils.isNotBlank(typeName)) {
            if (typeName.contains("雷达站") || typeName.contains("导弹阵地")) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", "0001");
                map.put("keyName", typeName.contains("雷达站") ? "探测距离(m)" : "防卫距离(m)");
                map.put("key", "radius");
                map.put("keyType", "Double");
                map.put("showType", "text");
                map.put("required", true);
                map.put("info", true);
                map.put("dataRange", "");
                map.put("enumerator", "[]");
                map.put("row", "");
                map.put("message", "此处不能为空");
                map.put("min", "");
                map.put("max", "");
                map.put("verify", true);
                lists.add(map);
            }
        }
        return lists;
    }

}